package com.tianheng.wanzhou.datacollecting.netty.kongyajiLuoGan.client;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.DataCollectingApplication;
import com.tianheng.wanzhou.datacollecting.db.entity.AirCompressorAmpsHis;
import com.tianheng.wanzhou.datacollecting.db.entity.AirCompressorLuogan;
import com.tianheng.wanzhou.datacollecting.db.entity.AirCompressorPowerHis;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IAirCompressorAmpsHisService;
import com.tianheng.wanzhou.datacollecting.db.service.IAirCompressorLuoganService;
import com.tianheng.wanzhou.datacollecting.db.service.IAirCompressorPowerHisService;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.SerializeUtil;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yujw
 * @Date: 2020/5/12 14:26
 * @Version 1.0
 */
@Slf4j
@Component(value = "kongyajiLuoganHandler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IAirCompressorLuoganService luoganService;

//    @Autowired
//    IAirCompressorAmpsHisService ampsHisService;
//
//    @Autowired
//    IAirCompressorPowerHisService powerHisService;

    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        luoganService = this.luoganService;
//        jedis = this.jedis;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 2).eq("status", 1).eq("son_type", "04");
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = inSocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
//        MachineList machine = (MachineList) SerializeUtil.deserialize(jedis.get(clientIP.getBytes()));
        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            if (str.substring(0,12).equals("FA0101010314")){
                DecimalFormat df = new DecimalFormat("0.00");
            String data = str.substring(12, str.length() - 4);
            AirCompressorLuogan airCompressor = new AirCompressorLuogan();
            airCompressor.setCompany(machine.getCompany());
            airCompressor.setWorkshop(machine.getWorkshop());
            airCompressor.setMachineIp(machine.getMacIp());
            airCompressor.setMachineId(machine.getMacId());
            airCompressor.setDischargePressure(StrUtil.hexStr2Int(data.substring(0, 4)).doubleValue()/100);
            airCompressor.setDischargeTemperature(StrUtil.hexStr2Int(data.substring(4, 8)).doubleValue()/10);
            airCompressor.setRuntime(StrUtil.hexStr2Int(data.substring(8, 12)));
            airCompressor.setLoadingTime(StrUtil.hexStr2Int(data.substring(12, 16)));
            airCompressor.setMotorAmps(StrUtil.hexStr2Int(data.substring(16, 20)).doubleValue()/10);
            airCompressor.setOilGasBarrelPressure(StrUtil.hexStr2Int(data.substring(20, 24)).doubleValue()/100);
            airCompressor.setOilGasBarrelTemperature(StrUtil.hexStr2Int(data.substring(24, 28)).doubleValue()/10);

            char[] s1 = StrUtil.hexStr2BinaryStr(data.substring(28, 32)).toCharArray();
            char[] s2 = StrUtil.hexStr2BinaryStr(data.substring(32, 36)).toCharArray();
            char[] s3 = StrUtil.hexStr2BinaryStr(data.substring(36, 40)).toCharArray();

            airCompressor.setLoadingSignal(Character.digit(s1[0], 2));
            airCompressor.setLoadingSignal(Character.digit(s1[1], 2));
            airCompressor.setRemoteControlSignal(Character.digit(s1[2], 2));
            airCompressor.setDischargeHighTemperature(Character.digit(s1[3], 2));
            airCompressor.setPhaseSequenceError(Character.digit(s1[4], 2));
            airCompressor.setHostOverload(Character.digit(s1[5], 2));
            airCompressor.setAirFilterFailure(Character.digit(s1[6], 2));
            airCompressor.setOilFineFault(Character.digit(s1[7], 2));
            airCompressor.setOilFilterFailure(Character.digit(s1[8], 2));
            airCompressor.setFanOverload(Character.digit(s1[9], 2));
            airCompressor.setSensorFault(Character.digit(s1[10], 2));
            airCompressor.setOilPressureAlarm(Character.digit(s1[11], 2));
            airCompressor.setMainContactorFeedbackFault(Character.digit(s1[12], 2));
            airCompressor.setFanFeedbackFault(Character.digit(s1[13], 2));
            airCompressor.setAbnormalPressure(Character.digit(s1[14], 2));
            airCompressor.setTooManyEmptyCars(Character.digit(s1[15], 2));

            airCompressor.setHeavyFail(Character.digit(s2[0], 2));
            airCompressor.setMinorFail(Character.digit(s2[1], 2));
            airCompressor.setPower(Character.digit(s2[2], 2));
            airCompressor.setMiddleStop(Character.digit(s2[3], 2));

            airCompressor.setRemoteStart(Character.digit(s3[0], 2));
            airCompressor.setRemoteStop(Character.digit(s3[1], 2));
            airCompressor.setForcedUninstall(Character.digit(s3[2], 2));

            //存储功耗电流等数据
//            AirCompressorPowerHis powerHis = new AirCompressorPowerHis();
//            AirCompressorAmpsHis ampsHis = new AirCompressorAmpsHis();
//            ampsHis.setMachineId(airCompressor.getMachineId());
//            ampsHis.setMachineIp(airCompressor.getMachineIp());
//            ampsHis.setWorkshop(airCompressor.getWorkshop());
//            ampsHis.setMotorAmps(airCompressor.getMotorAmps().toString());
//            ampsHisService.save(ampsHis);
//            powerHis.setMachineIp(airCompressor.getMachineIp());
//            powerHis.setMachineId(airCompressor.getMachineId());
//            powerHis.setPowerConsumption(airCompressor.getMotorAmps() * 1.2452);
//            powerHis.setWorkshop(airCompressor.getWorkshop());
//            powerHisService.save(powerHis);


            luoganService.saveOrUpdate(airCompressor);
            ctx.channel().close();
            ctx.close();
            }
        }finally {
            ReferenceCountUtil.release(msg);
        }
//        ctx.channel().close();
//        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
